package com.binance.healthcenter.telegram.invoker;

import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.telegram.telegrambots.meta.api.objects.Update;

import com.binance.healthcenter.telegram.command.TelegrambotCommand;
import com.binance.healthcenter.telegram.command.TelegrambotCommandMatcher;
import com.google.common.collect.Maps;

@Component
public class TelegramInvoker implements ApplicationContextAware {

    // 用来存放命令和相应的command的映射关系
    private Map<String, TelegrambotCommand> commandMap = Maps.newHashMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 扫描带有 TelegrambotCommandMatcher 注解的类并初始化 commandMap 对象
        Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(TelegrambotCommandMatcher.class);
        if (MapUtils.isEmpty(serviceBeanMap)) {
            return;
        }
        for (Object serviceBean : serviceBeanMap.values()) {
            TelegrambotCommandMatcher telegrambotCommandMatcher =
                    serviceBean.getClass().getAnnotation(TelegrambotCommandMatcher.class);
            String commandMatcher = telegrambotCommandMatcher.value();
            commandMap.put(commandMatcher, (TelegrambotCommand) serviceBean);
        }
    }

    public void action(Update update) {
        // 遍历commandMap，寻找到匹配的command，然后执行
        PathMatcher matcher = new AntPathMatcher();
        for (Map.Entry<String, TelegrambotCommand> entry : commandMap.entrySet()) {
            if (matcher.match(entry.getKey(), update.getMessage().getText())) {
                TelegrambotCommand telegrambotCommand = entry.getValue();
                telegrambotCommand.execute(update);
            }
        }
    }
}
